package cn.zwxky.android.user.Utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.facebook.drawee.backends.pipeline.Fresco;
import com.facebook.drawee.interfaces.DraweeController;
import com.facebook.drawee.view.SimpleDraweeView;
import com.facebook.imagepipeline.common.ResizeOptions;
import com.facebook.imagepipeline.request.ImageRequest;
import com.facebook.imagepipeline.request.ImageRequestBuilder;
import com.zgscwjm.lsfbbasetemplate.Event.LsfbEvent;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.LsfbAppManager;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.net.MD5;
import com.zgscwjm.lsfbbasetemplate.utils.DensityUtils;
import com.zgscwjm.lsfbbasetemplate.utils.LsfbLog;
import com.zgscwjm.lsfbbasetemplate.utils.SPUtils;
import com.zgscwjm.lsfbbasetemplate.view.banner.LsfbBanner;
import com.zgscwjm.lsfbbasetemplate.view.titlebar.LsfbTitleBar;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import cn.zwxky.android.user.News.BannerBean;
import cn.zwxky.android.user.R;


/**
 * 小工具类
 * Created by Administrator on 2016/8/16 0016.
 */
public class LittleUtils {

    /**
     * 经度
     */
    public static String address_jindu="";
    /**
     * 纬度
     */
    public static String address_weidu="";
    /**
     * 海拔
     */
    public static String address_haiba="0";

    /**
     * 昵称
     */
    public static String nikename="";
    /**
     * 头像
     */
    public static String img_head="";
    /**
     * 电话
     */
    public static String phone="";
    /**
     * 未读消息数量
     */
    public static String badg="";



    public static String DDtoDMS(Double d){

        String[] array=d.toString().split("[.]");
        String degrees=array[0];//得到度

        Double m=Double.parseDouble("0."+array[1])*60;
        String[] array1=m.toString().split("[.]");
        String minutes=array1[0];//得到分

        Double s=Double.parseDouble("0."+array1[1])*60;
        String[] array2=s.toString().split("[.]");
        String seconds=array2[0];//得到秒
        System.out.println(degrees+"  "+minutes+"  "+seconds);
        return degrees+"°"+minutes+"′"+seconds+"″";
    }

    /**
     * titlebar
     *
     * @param activity
     * @param title
     * @return
     */
    public static LsfbTitleBar setsimpletitlebar(LsfbActivity activity, String title) {
        LsfbTitleBar titleBar = activity.getTitleBar();
        ImageView back = backbtn2(activity);
        titleBar.setTitleText(title, Color.WHITE);
        titleBar.setTitleBarColor(activity.getResources().getColor(R.color.theme_color));
        activity.settitleBarHeight(DensityUtils.dp2px(activity, 56));
        titleBar.setLeftView(back, DensityUtils.dp2px(activity, 5), 0, 0, 0);
//        titleBar.setLeftImg(R.drawable.img_ngt_back);
        return titleBar;
    }

    /**
     * title右侧的文字按钮
     *
     * @param context
     * @param editstring
     * @return
     */
    public static TextView rightbtn(Context context, String editstring) {
        TextView textView = new TextView(context);
        textView.setText(editstring);
        textView.setTextColor(context.getResources().getColor(R.color.white_color));
        textView.setTextSize(15);
        return textView;
    }

    /**
     * title右侧的图片按钮
     *
     * @param context
     * @return
     */
    public static ImageView backbtn2(final Activity context) {
        ImageView imageView = new ImageView(context);
//        imageView.setImageResource(R.mipmap.img_back);
        imageView.setImageResource(R.drawable.btn_back);
        ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(DensityUtils.dp2px(context, 50), DensityUtils.dp2px(context, 22));
        imageView.setLayoutParams(params);
        imageView.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
//                CommonUtils.closeactivity(context);
                LsfbAppManager.getAppManager().finishActivity(context.getClass());
            }
        });
        return imageView;
    }

    /**
     * 压缩图片
     *
     * @param iv
     * @param filepath
     */
    public static void set50img(SimpleDraweeView iv, String filepath) {
//        SimpleDraweeView iv = viewHolder.getView(resid);
        Uri uri = Uri.parse(filepath);
        int width = 50, height = 50;
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
                .setResizeOptions(new ResizeOptions(width, height))
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setOldController(iv.getController())
                .setAutoPlayAnimations(true)
                .setImageRequest(request)
                .build();
//                            iv.setImageURI(Uri.parse("file://" + file.getPath()));
        iv.setController(controller);

//        iv.postInvalidate();
    }

    /**
     * 保存裁剪之后的图片数�?
     *
     * @param data
     */
    public static File getImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            ByteArrayOutputStream logoStream = new ByteArrayOutputStream();
            boolean res = photo.compress(Bitmap.CompressFormat.PNG, 100,
                    logoStream);// 将图像读取到logoStream�?
            byte[] logoBuf = logoStream.toByteArray();// 将图像保存到byte[]�?
            Bitmap temp = BitmapFactory.decodeByteArray(logoBuf, 0,
                    logoBuf.length);// 将图像从byte[]中读取生成Bitmap 对象 temp
            return saveMyBitmap("cysj" + System.currentTimeMillis(), temp);// 将图像保存到SD卡中
        }
        return null;
    }

    public static File saveMyBitmap(String bitName, Bitmap mBitmap) {
        File f = new File(Environment.getExternalStorageDirectory().getPath()
                + "/tempw" + bitName + ".png");
        if (f.exists()) {
            f.delete();
        }
//        CommonValue.uploadFile = Environment.getExternalStorageDirectory()
//                .getParent() + "/tempw" + bitName + ".png";
        try {
            f.createNewFile();

        } catch (IOException e) {
            Log.e("MyselfPresenterImpl", e.getMessage());
        }
        FileOutputStream fOut = null;
        try {
            fOut = new FileOutputStream(f);
        } catch (Exception e) {
            e.printStackTrace();
        }

        mBitmap.compress(Bitmap.CompressFormat.PNG, 100, fOut);
        try {
            fOut.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        try {
            fOut.close();

        } catch (IOException e) {
            e.printStackTrace();
        }

        return f;
    }

    public static String getActivityName(Context context) {
        String contextString = context.toString();
        contextString = contextString.toString().substring(contextString.lastIndexOf(".") + 1, contextString.indexOf("@"));
        return contextString;

    }


    public static void initBanner(LsfbBanner banner, List<BannerBean.ListBean> list, Context context, LsfbBanner.BannerOnItemClickLister bannerOnItemClickLister) {

        if (list != null && list.size() != 0 && banner != null) {
            banner.removeAllViews();
            banner.stopPlay();
            for (BannerBean.ListBean bean : list) {
                LsfbLog.e("banner添加了");
                View tmpview = LayoutInflater.from(context).inflate(R.layout.iv_banner, null);

//                SimpleDraweeView simpleDraweeView = new SimpleDraweeView(context);
                SimpleDraweeView simpleDraweeView = (SimpleDraweeView) tmpview.findViewById(R.id.img_banner);
                TextView textView= (TextView) tmpview.findViewById(R.id.btn_goto);
                Uri uri;
                uri = Uri.parse(URLString.IMG_URL + bean.getImg());
                simpleDraweeView.setImageURI(uri);
                textView.setText(bean.getTitle());
                banner.addView(tmpview);
            }
            banner.setmOnItemClickLister(bannerOnItemClickLister);
            banner.startPlay();
        }
    }

    /**
     * 检查当前网络是否可用
     * @param
     * @return
     */

    public static boolean isNetworkAvailable(Activity activity)
    {
        Context context = activity.getApplicationContext();
        // 获取手机所有连接管理对象（包括对wi-fi,net等连接的管理）
        ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);

        if (connectivityManager == null)
        {
            return false;
        }
        else
        {
            // 获取NetworkInfo对象
            NetworkInfo[] networkInfo = connectivityManager.getAllNetworkInfo();

            if (networkInfo != null && networkInfo.length > 0)
            {
                for (int i = 0; i < networkInfo.length; i++)
                {
                    System.out.println(i + "===状态===" + networkInfo[i].getState());
                    System.out.println(i + "===类型===" + networkInfo[i].getTypeName());
                    // 判断当前网络状态是否为连接状态
                    if (networkInfo[i].getState() == NetworkInfo.State.CONNECTED)
                    {
                        return true;
                    }
                }
            }
        }
        return false;
    }


    public static void closeactivity(Activity context) {
        LsfbEvent.getInstantiation().unregister(context);
        context.finish();
    }


    public static String getToken(String url) {
        Date date = new Date();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd-HH");
        String temp3 = "";
        if (Config.TOKENTYPE == 1) {
            SimpleDateFormat temp1 = new SimpleDateFormat("HH-mm");
            temp3 = temp1.format(date);
        } else {
            temp3 = String.valueOf(date.getTime() / 1000L);
        }

        String temp11 = Config.Net_Token_Prefix;

        try {
            temp11 = temp11 + dateFormat.parse(dateFormat.format(date)).getTime() / 1000L;
        } catch (ParseException var6) {
            var6.printStackTrace();
        }

        temp11 = temp11 + Config.Net_Token_Suffix + url.substring(url.lastIndexOf("/") + 1);
        return "?version=" + "v1.0" + "&token=" + MD5.GetMD5Code(MD5.GetMD5Code(temp11)) + "&times=" + temp3;
    }


    public static String getTimeFromMillisecond(int second) {


        int h = second / 3600;
        int m = second % 3600 / 60;
        int s = second % 60;

        return String.format("%d:%02d:%02d", h, m, s);
    }


    /**
     * 保存方法
     */
    public static Boolean saveBitmap(String picName, Bitmap bm, Context context) {
        Log.e("nonsense", "保存图片");
        if (picName == null) {
            picName = "redmouth" + System.currentTimeMillis() + ".png";
        }
        File f = new File(Environment.getExternalStorageDirectory().getPath()
                + "/" + picName);
        if (f.exists()) {
            f.delete();
        }
        try {
            FileOutputStream out = new FileOutputStream(f);
            bm.compress(Bitmap.CompressFormat.PNG, 90, out);
            out.flush();
            out.close();
            Log.i("nonsense", "已经保存" + picName);
            Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
            Uri uri = Uri.fromFile(f);
            intent.setData(uri);
            context.sendBroadcast(intent);
            Log.i("nonsense", "已经刷新" + picName);
            return true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return false;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }
    }


    public static void loadimg(SimpleDraweeView iv, String filepath) {
//        SimpleDraweeView iv = viewHolder.getView(resid);
        Uri uri = Uri.parse(filepath);
        int width = 200, height = 200;
        ImageRequest request = ImageRequestBuilder.newBuilderWithSource(uri)
//                .setResizeOptions(new ResizeOptions(width, height))
                .setAutoRotateEnabled(true)
                .build();
        DraweeController controller = Fresco.newDraweeControllerBuilder()
                .setOldController(iv.getController())
                .setAutoPlayAnimations(true)
                .setImageRequest(request)
                .build();
//                            iv.setImageURI(Uri.parse("file://" + file.getPath()));
        iv.setController(controller);
        iv.postInvalidate();
    }

    public static void setWindowStatusBarColor(Activity activity, int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = activity.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(activity.getResources().getColor(colorResId));

                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void setWindowStatusBarColor(Dialog dialog, int colorResId) {
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                Window window = dialog.getWindow();
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(dialog.getContext().getResources().getColor(colorResId));

                //底部导航栏
                //window.setNavigationBarColor(activity.getResources().getColor(colorResId));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 保存userid
     */
    public static void saveuser(String id, Context context){
        SPUtils.remove(context,"userid1");
        SPUtils.put(context,"userid1",id);
    }
    public static void exit(Context context) {
        Config.setUserId("");
        SPUtils.remove(context, "userid1");
//        T.showShort(context, context.getResources().getString(R.string.new_login));
    }


    public static int getScreenHeight(Context context) {
        WindowManager wm = (WindowManager) context
                .getSystemService(Context.WINDOW_SERVICE);
        DisplayMetrics outMetrics = new DisplayMetrics();
        wm.getDefaultDisplay().getMetrics(outMetrics);
        return outMetrics.heightPixels;
    }

    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }




}



